﻿using System;
using DNT.RavenQA.Core.Extensions;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.RelyingParty;

namespace DNT.RavenQA.Core.Models
{
    public class OpenIdUser : User
    {
        public static User Build(IAuthenticationResponse response)
        {
            response.EnsureIsNotNull("response");

            OpenIdUser user = null;
            var claimResponseUntrusted = response.GetUntrustedExtension<ClaimsResponse>();
            var claimResponse = response.GetExtension<ClaimsResponse>();

            if (claimResponse.IsNotNull())
                user = Build(claimResponse, response.FriendlyIdentifierForDisplay);
            else if (claimResponseUntrusted.IsNotNull())
                user = Build(claimResponseUntrusted, response.FriendlyIdentifierForDisplay);

            return user;
        }

        public static OpenIdUser Build(ClaimsResponse claim, String identifier)
        {
            claim.EnsureIsNotNull("claim");
            identifier.EnsureIsNotNullOrEmpty("identifier");

            return new OpenIdUser
                       {
                           EmailAddress = claim.Email,
                           ProviderName = identifier
                       };
        }
    }
}